#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File        :百度验证码.py
@Time        :2020/08/26 19:28:18
@Author      :hejiang
@Software    :vsCode
'''
from PIL import Image
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import random


class LoginBaiDu(object):
    def __init__(self, url, password, username):
        self.url = url
        self.password = password
        self.username = username
        self.browser = self.getbrowser()
        self.run(self.browser)

    def getbrowser(self):
        chrome_options = webdriver.ChromeOptions()
        browser = webdriver.Chrome(
            options=chrome_options,
            executable_path='D:\chrome\chromedriver.exe')
        browser.get(self.url)
        # 清除cookies记录
        browser.delete_all_cookies()
        return browser

    def run(self, browser):
        # 找到登陆按钮
        browser.find_element_by_xpath("//div[@id='u1']/a[text()='登录']").click()
        # 等待网站加载
        browser.implicitly_wait(3)
        # 定位弹出框
        browser.current_window_handle
        # 找到用户名登录按钮,并点击登录
        browser.find_element_by_id('TANGRAM__PSP_10__footerULoginBtn').click()
        time.sleep(2)
        # 找到输入用户名的input标签，模拟输入用户名
        browser.find_element_by_id("TANGRAM__PSP_10__userName").send_keys(
            self.username)
        time.sleep(3)
        # 找到输入密码的input标签,模拟输入密码
        browser.find_element_by_id("TANGRAM__PSP_10__password").send_keys(
            self.password)
        time.sleep(10)
        # 对整个页面进行截图
        browser.get_screenshot_as_file('login.png')
        # 定位验证码的坐标
        code = browser.find_element_by_xpath(
            "//span[@class='pass-verifyCodeImgParent']\
        /img[@id='TANGRAM__PSP_10__verifyCodeImg']")
        # 计算验证码四个点的坐标
        left = code.location['x']
        top = code.location['y']
        right = code.location['x'] + code.size['width']
        bottom = code.location['y'] + code.size['height']
        print("验证码坐标::", left, top, right, bottom)
        # 利用python的图像处理库，将验证码切出来,保存验证码code.png到当前目录
        im = Image.open('login.png')
        im = im.crop((left, top, right, bottom))
        im.save('code.png')
        self.user_input(browser)

    def user_input(self, browser):
        # 查看code.png图片,手动输入验证码
        user_code = input("验证码:").strip()
        # 找到验证码的输入框，并将手动输入的验证码赋值到验证码输入框
        browser.find_element_by_id("TANGRAM__PSP_10__verifyCode").send_keys(
            user_code)
        # 找到登陆按钮，并点击登录
        browser.find_element_by_id("TANGRAM__PSP_10__submit").click()
        try:
            # 如果登陆成功，获取用户信息
            username = browser.find_element_by_id("s_username_top").text
            if username:
                print('登陆成功')
                print(username)
            # 登陆失败,打印错误信息
        except Exception as e:
            print("登陆失败错误信息:{}".format(e))
        finally:
            # 退出程序
            time.sleep(10)
            browser.quit()


if __name__ == '__main__':
    url = 'https://www.baidu.com'
    username = 'he123'
    password = 'h123'
    st = LoginBaiDu(username=username, password=password, url=url)